package com.richest.api.controller.pay;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.richest.api.controller.form.UnifiedOrderForm;
import com.richest.api.utils.AliAppInfo;
import com.richest.api.utils.GlobalNames;

/**
 * 
 * @author zhaohongchao 2019年3月26日 上午8:38:00
 * @email 70375739@qq.com
 */
public class AliPay {
	private Logger logger = LoggerFactory.getLogger(AliPay.class);

	/**
	 * @author zhaohongchao 2019年3月26日 上午8:38:16
	 * @email 70375739@qq.com
	 * @param parseObject
	 * @return
	 */
	public JSONObject aliUnifiedOrder(UnifiedOrderForm form) {
		JSONObject resultObject = new JSONObject();
		String strBody = "";
		// 实例化客户端
		AlipayClient alipayClient = new DefaultAlipayClient(AliAppInfo.getPayUrl(), AliAppInfo.getAppid(),
				AliAppInfo.getRsaPrivateKey(), AliAppInfo.getFormat(), AliAppInfo.getCharSet(),
				AliAppInfo.getAliPayPublicKey(), AliAppInfo.getSignType());
		// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		// SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setBody(form.getBody());
		model.setSubject("聚宝同城-就餐订单支付");
		model.setOutTradeNo(form.getOut_trade_no());
		model.setTimeoutExpress("30m");
		model.setTotalAmount(form.getTotal_fee());
		model.setProductCode("QUICK_MSECURITY_PAY");
		model.setPassbackParams(form.getAdmart_id());
		request.setBizModel(model);
		request.setNotifyUrl(AliAppInfo.getNotifyUrl());
		try {
			// 这里和普通的接口调用不同，使用的是sdkExecute
			AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
			strBody = response.getBody();
			logger.debug(strBody);// 就是orderString 可以直接给客户端请求，无需再做处理。
			/**
			 * 组织输出结果JSON串
			 */
			resultObject.put("result", GlobalNames.CALL_RESULT_SUCC);
			resultObject.put("errmessage", "");
			resultObject.put("alipay", strBody);
		} catch (AlipayApiException e) {
			logger.debug(e.getMessage());
			resultObject.put("result", GlobalNames.CALL_RESULT_FAIL);
			resultObject.put("errmessage", "下单失败!原因：" + e.getMessage());
			return resultObject;
		}
		return resultObject;
	}

}
